package org.chinasoft.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.chinasoft.entity.Menu;
import org.chinasoft.entity.Role;
import org.chinasoft.entity.User;
import org.chinasoft.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;

    /**
     * 给当前用户授权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 获取当前用户
        User user = (User) principals.getPrimaryPrincipal();

        // 设置当前用户角色
        Set<String> roleSet = new HashSet<>();
        // 设置当前用户权限
        Set<String> permissionSet = new HashSet<>();

        for (Role role : user.getRoleSet()) {
            // 获取角色名
            String roleName = role.getName();

            // 获取角色拥有的权限
            for (Menu menu : role.getMenuSet()) {
                // 添加权限标识符
                permissionSet.add(menu.getPermission());
            }
            // 添加角色到角色集合中
            roleSet.add(roleName);
        }
        // 添加到shiro框架中
        authorizationInfo.addRoles(roleSet);
        authorizationInfo.addStringPermissions(permissionSet);
        return authorizationInfo;
    }

    /**
     * 鉴定当前用户
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();

        // 通过用户名查询数据库
        User user = userService.findByUsername(username);
        if (user == null) {
            // 没找到帐号抛出异常
            throw new UnknownAccountException();
        }
        return new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());
    }
}
